import cv2
import numpy as np

# ====== 修复：添加 Haar 级联分类器初始化 ======
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# 检查模型是否加载成功
if face_cascade.empty():
    print("错误：人脸检测模型未加载")
    exit()

# 加载训练好的识别模型和标签
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('face_model.yml')
label_dict = np.load('label_dict.npy', allow_pickle=True).item()

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 转换为灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(50, 50)
    )

    # 识别并标注
    for (x, y, w, h) in faces:
        face_roi = gray[y:y + h, x:x + w]
        face_resized = cv2.resize(face_roi, (100, 100))  # 与训练尺寸一致

        label, confidence = recognizer.predict(face_resized)
        name = label_dict.get(label, "Unknown")

        # 绘制结果
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.putText(frame, f"{name} ({confidence:.2f})", (x, y - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)

    cv2.imshow('Real-time Face Recognition', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows() 